package com.gxc.graph;

import java.util.HashSet;
import java.util.Set;
import java.util.Stack;

/**
 * 深度优先
 */
public class DepthFirst {

    public static void main(String[] args) {
        Graph graph = BreadthFirst.createGraph();

        depth_First(graph);
    }

    /**
     * 深度优先遍历
     * @param graph
     */
    private static void depth_First(Graph graph) {
        Stack<Node> stack = new Stack<>();
        stack.push(graph.nodes.get(1));
        //确保已经遍历过的node不再处理
        Set<Node> set = new HashSet<>();
        set.add(graph.nodes.get(1));
        System.out.print(graph.nodes.get(1).value + " ");
        while (!stack.isEmpty()) {
            Node node = stack.pop();
            for (Node next : node.nexts) {
                if (!set.contains(next)) {
                    System.out.print(next.value + " ");
                    stack.push(node);
                    stack.push(next);
                    set.add(next);
                    break;
                }
            }
        }
    }

}
